<?php
require_once __DIR__ . '/config.php';

// 工具函数：获取指定类型的奖惩
function get_praises($type, $max = 20) {
    global $pdo;
    $max = intval($max);
    $stmt = $pdo->prepare("SELECT * FROM praises WHERE type=:type AND is_active=1 ORDER BY display_order ASC, id DESC LIMIT $max");
    $stmt->bindValue(':type', $type);
    $stmt->execute();
    return $stmt->fetchAll();
}

// 工具函数：获取所有奖惩（用于管理页面）
function get_all_praises() {
    global $pdo;
    $stmt = $pdo->query("SELECT * FROM praises ORDER BY type, display_order ASC, updated_at DESC");
    return $stmt->fetchAll();
}

// 处理管理页面的表单提交（增删改）
function handle_praise_actions() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) {
        return;
    }
    global $pdo;

    // 记录调试日志
    file_put_contents('debug_post.log', print_r($_POST, true), FILE_APPEND);

    switch ($_POST['action']) {
        // 增加奖惩
        case 'add':
            $title = $_POST['title'];
            $content = $_POST['content'];
            $type = $_POST['type'];
            if (!in_array($type, ['praise', 'criticism'])) {
                die('奖惩类型不合法');
            }
            $display_order = intval($_POST['display_order']);
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $stmt = $pdo->prepare("INSERT INTO praises (title, content, type, display_order, is_active) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$title, $content, $type, $display_order, $is_active]);
            break;

        // 修改奖惩
        case 'edit':
            $id = intval($_POST['id']);
            $title = $_POST['title'];
            $content = $_POST['content'];
            $type = $_POST['type'];
            if (!in_array($type, ['praise', 'criticism'])) {
                die('奖惩类型不合法');
            }
            $display_order = intval($_POST['display_order']);
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE praises SET title=?, content=?, type=?, display_order=?, is_active=? WHERE id=?");
            $stmt->execute([$title, $content, $type, $display_order, $is_active, $id]);
            break;

        // 删除奖惩
        case 'delete':
            $id = intval($_POST['id']);
            $stmt = $pdo->prepare("DELETE FROM praises WHERE id=?");
            $stmt->execute([$id]);
            break;
    }

    // 重定向到管理页面
    $manageParam = isset($_GET['manage']) ? intval($_GET['manage']) : 1;
    header("Location: praise_manage.php?manage=$manageParam");
    exit;
}